package com.example.zhbj;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Window;
import android.view.WindowManager;

import com.example.zhbj.fragment.ContentFragment;
import com.example.zhbj.fragment.LeftMenuFragment;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;

/**
 * 主页面
 *
 * 当一个activity要展示Fragment时，必须要继承FragmentActivity
 */
public class MainActivity extends SlidingFragmentActivity {

    /**
     * 定义“内容”碎片的标志
     */
    private static final String TAG_CONTENT = "TAG_CONTENT";

    /**
     * 定义“侧边栏”碎片的标志
     */
    private static final String TAG_LEFT_MENU = "TAG_LEFT_MENU";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        // 设置侧边栏的布局
        setBehindContentView(R.layout.left_menu);

        // 获取当前侧边栏对象
        SlidingMenu slidingMenu = getSlidingMenu();
        // 设置侧边栏的触摸模式为全屏触摸
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        // 设置侧边栏为左右都有的模式，不然默认只展现一个
        // slidingMenu.setMode(SlidingMenu.LEFT_RIGHT);
        // 设置右侧的侧边栏
        // slidingMenu.setSecondaryMenu(res);
        // 设置侧边栏的宽度
        WindowManager wm = (WindowManager)getSystemService(WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth(); // 获取宽度

        slidingMenu.setBehindOffset(width * 260/480);// 屏幕预留200px的宽度，使用代码适配按比例来展示侧边栏
        initFragment();
    }

    /**
     * 初始化Fragment
     */
    private void initFragment(){
        // 获取Fragment管理器
        FragmentManager fragmentManager = getSupportFragmentManager();
        // FragmentManager开启一个事务
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fl_content,new ContentFragment(),TAG_CONTENT); // 使用fragment替换现有布局，第一个参数表示当前布局的id，第二个参数表示要替换的Fragment对象
        fragmentTransaction.replace(R.id.fl_left_menu,new LeftMenuFragment(),TAG_LEFT_MENU); // 第三个参数为打一个标记，可以调用这个碎片对象
        fragmentTransaction.commit(); // 提交事务
        //fragmentManager.findFragmentByTag(TAG); // 通过Tag找到fragment对象
    }

    /**
     * 获取侧边栏的fragment对象
     */
    public LeftMenuFragment getLeftMenuFragment(){
        FragmentManager fragmentManager = getSupportFragmentManager();
        LeftMenuFragment fragment = (LeftMenuFragment) fragmentManager.findFragmentByTag(TAG_LEFT_MENU);
        return fragment;
    }

    /**
     * 获取主页的fragment对象
     */
    public ContentFragment getContentFragment(){
        FragmentManager fragmentManager = getSupportFragmentManager();
        ContentFragment fragment = (ContentFragment) fragmentManager.findFragmentByTag(TAG_CONTENT);
        return fragment;
    }
}
